// app.js
const util = require("utils/util.js");

App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync("logs") || [];
    logs.unshift(Date.now());
    wx.setStorageSync("logs", logs);

    // 检查用户是否已登录
    const userInfo = wx.getStorageSync("userInfo");

    // 检查access_token
    this.checkAndSetAccessToken(userInfo);

    if (!userInfo) {
      // 用户未登录，跳转到登录页面
      wx.redirectTo({
        url: "/pages/login/login",
      });
    } else {
      // 用户已登录，跳转到主页
      // 使用switchTab而不是redirectTo，因为home页面是tabBar页面
      wx.switchTab({
        url: "/pages/home/home",
        fail: (err) => {
          console.error("切换到首页失败:", err);
          // 如果switchTab失败，尝试redirectTo
          wx.redirectTo({
            url: "/pages/home/home",
          });
        },
      });
    }

    // 初始化音频管理器
    this.initAudioManager();
  },

  // 检查并设置access_token
  checkAndSetAccessToken: function (userInfo) {
    console.log("检查access_token状态");
    const token = wx.getStorageSync("access_token");

    // 如果没有token但有用户信息，创建临时token
    if (!token && userInfo && userInfo.userId) {
      console.log("应用启动时发现用户已登录但无token，创建临时token");
      const tempToken = `temp_token_${userInfo.userId}_${Date.now()}`;
      wx.setStorageSync("access_token", tempToken);
      console.log("已创建临时token:", tempToken);
    }
  },

  // 初始化音频管理器
  initAudioManager: function () {
    this.audioManager = wx.getBackgroundAudioManager();

    // 监听音频播放事件
    this.audioManager.onPlay(() => {
      this.globalData.isPlaying = true;
      this.updatePlayStatus(true);
    });

    // 监听音频暂停事件
    this.audioManager.onPause(() => {
      this.globalData.isPlaying = false;
      this.updatePlayStatus(false);
    });

    // 监听音频停止事件
    this.audioManager.onStop(() => {
      this.globalData.isPlaying = false;
      this.updatePlayStatus(false);
    });

    // 监听音频自然播放结束事件
    this.audioManager.onEnded(() => {
      // 播放下一首
      this.playNextSong();
    });

    // 监听音频播放错误事件
    this.audioManager.onError((err) => {
      console.error("音频播放错误:", err);
      wx.showToast({
        title: "播放失败，请重试",
        icon: "none",
      });
    });
  },

  // 更新播放状态
  updatePlayStatus: function (isPlaying) {
    console.log("App 更新播放状态:", isPlaying ? "播放" : "暂停");
    this.globalData.isPlaying = isPlaying;

    // 尝试直接控制背景音频
    try {
      const bgAudioManager = wx.getBackgroundAudioManager();
      if (bgAudioManager && bgAudioManager.src) {
        if (
          isPlaying &&
          (bgAudioManager.paused || bgAudioManager.currentTime === 0)
        ) {
          console.log("App 尝试播放音频");
          bgAudioManager.play();
        } else if (!isPlaying && !bgAudioManager.paused) {
          console.log("App 尝试暂停音频");
          bgAudioManager.pause();
        }
      }
    } catch (error) {
      console.error("App 控制音频失败:", error);
    }

    // 通知页面更新播放状态
    if (this.playStatusCallback) {
      console.log("App 调用播放状态回调");
      this.playStatusCallback(isPlaying);
    }
  },

  // 播放歌曲
  playSong: function (song) {
    if (!song || !song.id) return;

    const token = wx.getStorageSync("access_token");
    const that = this;

    // 获取歌曲URL
    wx.request({
      url: "https://smartsound.top/song/url",
      method: "GET",
      data: {
        id: song.id,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        if (
          res.data &&
          res.data.data &&
          res.data.data[0] &&
          res.data.data[0].url
        ) {
          const songUrl = res.data.data[0].url;

          // 更新当前播放歌曲信息
          that.globalData.nowPlaying = {
            id: song.id,
            title: song.name,
            artist:
              song.artist ||
              (song.ar && song.ar[0].name) ||
              (song.artists && song.artists[0].name) ||
              "未知歌手",
            coverUrl:
              song.picUrl ||
              (song.al && song.al.picUrl) ||
              (song.album && song.album.picUrl) ||
              "",
            duration: song.duration || 0,
          };

          // 设置音频信息
          that.audioManager.title = that.globalData.nowPlaying.title;
          that.audioManager.singer = that.globalData.nowPlaying.artist;
          that.audioManager.coverImgUrl = that.globalData.nowPlaying.coverUrl;
          that.audioManager.src = songUrl;

          // 更新播放状态
          that.globalData.isPlaying = true;

          // 保存当前播放列表
          if (
            that.globalData.currentSongList &&
            !that.globalData.currentSongList.some((item) => item.id === song.id)
          ) {
            that.globalData.currentSongList.unshift(song);
          }

          // 通知页面更新
          if (that.songChangeCallback) {
            that.songChangeCallback(that.globalData.nowPlaying);
          }

          // 上传播放记录
          that.uploadSongPlayRecord(song);
        } else {
          wx.showToast({
            title: "暂无版权或VIP歌曲",
            icon: "none",
          });
        }
      },
      fail(err) {
        console.error("获取歌曲URL失败:", err);
        wx.showToast({
          title: "获取歌曲失败",
          icon: "none",
        });
      },
    });
  },

  // 上传歌曲播放记录
  uploadSongPlayRecord: function (song) {
    if (!song || !song.id) return;

    // 准备歌手信息
    let artists = [];
    if (song.ar && song.ar.length > 0) {
      artists = song.ar.map((artist) => ({
        id: artist.id,
        name: artist.name,
      }));
    } else if (song.artists && song.artists.length > 0) {
      artists = song.artists.map((artist) => ({
        id: artist.id,
        name: artist.name,
      }));
    } else if (song.artist) {
      // 如果只有artist字符串，尝试查找完整的歌手信息
      const currentSongList = this.globalData.currentSongList || [];
      const fullSong = currentSongList.find((s) => s.id === song.id);

      if (fullSong && fullSong.ar) {
        artists = fullSong.ar.map((artist) => ({
          id: artist.id,
          name: artist.name,
        }));
      } else {
        // 没有详细信息时提供基本信息
        artists = [
          {
            id: 0,
            name: song.artist,
          },
        ];
      }
    }

    // 准备歌曲时长
    let dt = 0;
    if (song.dt) {
      dt = song.dt;
    } else if (song.duration) {
      dt = song.duration * 1000;
    } else if (this.audioManager && this.audioManager.duration) {
      dt = this.audioManager.duration * 1000;
    }

    // 上传记录
    util
      .uploadPlayRecord({
        id: song.id,
        name: song.name || song.title,
        artists: artists,
        dt: dt,
      })
      .then((res) => {
        console.log("成功上传播放记录");
      })
      .catch((err) => {
        console.error("上传播放记录失败:", err);
      });
  },

  // 播放下一首歌曲
  playNextSong: function () {
    if (
      !this.globalData.currentSongList ||
      this.globalData.currentSongList.length <= 1
    )
      return;

    const currentId = this.globalData.nowPlaying.id;
    const currentIndex = this.globalData.currentSongList.findIndex(
      (song) => song.id === currentId
    );

    if (currentIndex !== -1) {
      const nextIndex =
        (currentIndex + 1) % this.globalData.currentSongList.length;
      this.playSong(this.globalData.currentSongList[nextIndex]);
    }
  },

  // 播放上一首歌曲
  playPrevSong: function () {
    if (
      !this.globalData.currentSongList ||
      this.globalData.currentSongList.length <= 1
    )
      return;

    const currentId = this.globalData.nowPlaying.id;
    const currentIndex = this.globalData.currentSongList.findIndex(
      (song) => song.id === currentId
    );

    if (currentIndex !== -1) {
      const prevIndex =
        (currentIndex - 1 + this.globalData.currentSongList.length) %
        this.globalData.currentSongList.length;
      this.playSong(this.globalData.currentSongList[prevIndex]);
    }
  },

  // 通过ID播放歌曲
  playSongById: function (songId) {
    if (!songId) return;

    const token = wx.getStorageSync("access_token");
    const that = this;

    // 先获取歌曲详情
    wx.request({
      url: "https://smartsound.top/song/detail",
      method: "GET",
      data: {
        ids: songId,
      },
      header: {
        Authorization: token ? `Bearer ${token}` : "",
        "content-type": "application/json",
      },
      success(res) {
        if (res.data && res.data.songs && res.data.songs.length > 0) {
          // 播放获取到的歌曲
          that.playSong(res.data.songs[0]);
        } else {
          wx.showToast({
            title: "获取歌曲信息失败",
            icon: "none",
          });
        }
      },
      fail(err) {
        console.error("获取歌曲详情失败:", err);
        wx.showToast({
          title: "获取歌曲失败",
          icon: "none",
        });
      },
    });
  },

  globalData: {
    userInfo: null,
    apiBaseUrl: "https://smartsound.top", // 音乐相关API基础URL（使用HTTP）
    deviceApiBaseUrl: "https://smartsound.top", // 设备相关API基础URL（使用HTTPS）
    // 音乐播放相关
    nowPlaying: {
      id: null,
      title: "暂无播放",
      artist: "未知歌手",
      coverUrl: "",
      duration: 0,
    },
    isPlaying: false,
    currentSongList: [], // 当前播放列表
  },
});

// 登录
wx.login({
  success: (res) => {
    // 发送 res.code 到后台换取 openId, sessionKey, unionId
  },
});
